package com.passive.lock.service.key.imp;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.passive.lock.mapper.TKeyMapper;
import com.passive.lock.mapper.TKeyMapperCustom;
import com.passive.lock.mapper.TUserMapper;
import com.passive.lock.model.po.TKey;
import com.passive.lock.model.po.TKeyExample;
import com.passive.lock.model.po.TUser;
import com.passive.lock.model.vo.TKeyVo;
import com.passive.lock.service.key.KeyService;
import com.passive.lock.utils.DozerMapperUtils;
import com.passive.lock.utils.Result;

@Service("keyService")
public class KeyServiceImpl implements KeyService {

	@Resource(name = "TKeyMapper")
	private TKeyMapper keyMapper;
	@Resource(name = "TKeyMapperCustom")
	private TKeyMapperCustom keyMapperCustom;

	@Resource(name = "TUserMapper")
	private TUserMapper userMapper;

	@Override
	public Result addKey(TKeyVo tKeyVo) {
		try {
			TKey tKey = new TKey();
			DozerMapperUtils.map(tKeyVo, tKey);
			TUser tuser = userMapper.selectByPrimaryKey(tKey.getUserid());
			tKey.setUsername(tuser.getName());
			keyMapper.insert(tKey);
			return Result.ok();
		} catch (Exception e) {
			return Result.build(500, "请联系系统管理员");
		}
	}

	@Override
	public List<TKey> keyList(String groupid, String deptId, String keyName, String userName, String keynote,
			String keystate, Integer offset, Integer limit) {
		return keyMapperCustom.keyList(groupid, deptId, keyName, userName, keynote, keystate, offset, limit);

	}

	@Override
	public int keyListCount(String groupid, String deptId, String keyName, String userName, String keyNote,
			String keyState) {
		return keyMapperCustom.keyListCount(groupid, deptId, keyName, userName, keyNote, keyState);
	}

	@Override
	public Result updateKey(TKeyVo tKeyVo) {
		try {
			TKey tKey = new TKey();
			DozerMapperUtils.map(tKeyVo, tKey);
			keyMapper.updateByPrimaryKey(tKey);
			return Result.ok();
		} catch (Exception e) {
			return Result.build(500, "请联系系统管理员");
		}
	}

	@Override
	public Result deleteKey(TKeyVo tKeyVo) {
		keyMapper.deleteByPrimaryKey(tKeyVo.getKeyid());
		return Result.ok();
	}

	@Override
	public Result deleteKeyList(List<Integer> tKeyids) {
		for (Integer tKeyid : tKeyids) {
			keyMapper.deleteByPrimaryKey(tKeyid);
		}
		return Result.ok();
	}

	@Override
	public Result queryKeyList(String deptid) {
		TKeyExample example = new TKeyExample();
		TKeyExample.Criteria criteria = example.createCriteria();
		criteria.andDeptidEqualTo(deptid);
		List<TKey> list = keyMapper.selectByExample(example);
		return Result.ok(list);
	}
}
